package com.woshengqile.controller.admin;

import net.hasor.core.Inject;

import com.jfinal.aop.Clear;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.upload.UploadFile;
import com.woshengqile.FileType;
import com.woshengqile.Message;
import com.woshengqile.Setting;
import com.woshengqile.Setting.CaptchaType;
import com.woshengqile.Setting.Locale;
import com.woshengqile.Setting.RoundType;
import com.woshengqile.Setting.WatermarkPosition;
import com.woshengqile.interceptor.CsrfInterceptor;
import com.woshengqile.service.CacheService;
import com.woshengqile.service.FileService;
import com.woshengqile.util.EnumUtils;
import com.woshengqile.util.ObjectUtils;
import com.woshengqile.util.SystemUtils;

/**
 * Controller - 系统设置
 * 
 */
@ControllerBind(controllerKey = "/admin/setting")
public class SettingController extends BaseController {

	@Inject
	private FileService fileService;
	@Inject
	private CacheService cacheService;

	/**
	 * 编辑
	 */
	public void edit() {
		setAttr("setting", SystemUtils.getSetting());
		setAttr("locales", Setting.Locale.values());
		setAttr("watermarkPositions", Setting.WatermarkPosition.values());
		setAttr("roundTypes", Setting.RoundType.values());
		setAttr("captchaTypes", Setting.CaptchaType.values());
		render("/admin/setting/edit.ftl");
	}

	/**
	 * 更新
	 */
	@Clear(CsrfInterceptor.class)
	public void update() {
		UploadFile watermarkImageFile = getFile("watermarkImageFile");
		Setting setting = getBean(Setting.class);
		
		setting.setWatermarkPosition(EnumUtils.convert(WatermarkPosition.class, getPara("watermarkPosition")));
		setting.setPriceRoundType(EnumUtils.convert(RoundType.class, getPara("priceRoundType")));
		setting.setLocale(EnumUtils.convert(Locale.class, getPara("locale")));
		
		// 验证码类型
		String[] captchaTypeNames = getParaValues("captchaTypes");
		if (!ObjectUtils.isEmpty(captchaTypeNames)) {
			int length = captchaTypeNames.length;
			CaptchaType [] captchaTypes = new CaptchaType [length];
			for (int i = 0; i < length; i++) {  
				captchaTypes[i] = CaptchaType.valueOf(captchaTypeNames[i]); 
			}  
			setting.setCaptchaTypes(captchaTypes);
		}
		
		Setting srcSetting = SystemUtils.getSetting();
		if (watermarkImageFile != null && watermarkImageFile.getFile().length() <= 0) {
			if (!fileService.isValid(FileType.image, watermarkImageFile)) {
				addFlashMessage(Message.error("admin.upload.invalid"));
				redirect("edit");
			}
			String watermarkImage = fileService.uploadLocal(FileType.image, watermarkImageFile);
			setting.setWatermarkImage(watermarkImage);
		} else {
			setting.setWatermarkImage(srcSetting.getWatermarkImage());
		}

		SystemUtils.setSetting(setting);
		cacheService.clear();

		addFlashMessage(SUCCESS_MESSAGE);
		redirect("edit");
	}

}